package com.lusang.gift.service.impl;

import com.lusang.gift.service.IUserService;
import org.apache.commons.lang.StringUtils;
import com.lusang.gift.clients.LoginUserClient;
import com.lusang.gift.constants.SmsContants;
import com.lusang.gift.domain.LoginUser;
import com.lusang.gift.domain.User;
import com.lusang.gift.dto.RegisterDto;
import com.lusang.gift.mapper.UserMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lusang.gift.util.AjaxResult;
import com.lusang.gift.util.StrUtils;
import com.lusang.gift.util.encrypt.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginUserClient loginUserClient;
    @Value("${sms.code.register.resend-time}")
    private Integer resendTime;//消息重发时间
    @Value("${sms.code.register.expire-time}")
    private Integer expireTime;//验证码过期时间
    @Override
    public AjaxResult sendSMS(RegisterDto dto) {
        String tel = dto.getTel();
        //判断手机号是否已经被注册了
        User user = userMapper.loadByPhone(tel);
        if (user!=null){
            return AjaxResult.me().setSuccess(false).setMessage("该手机号已被注册，请登陆");
        }
        //判断短信验证码是否存在 redis中 保存格式设置成 code:time  验证码和生成时间
        String key = SmsContants.SMSCODE_KEY + tel;
        String smsCodeOfRedis = (String)redisTemplate.opsForValue().get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {//不存在就产生新的
            code = StrUtils.getRandomString(6);
        }else {//存在 就用存在的
            //判断两次发送验证码过了重发时间没 没过就可能是恶意请求 报错
            code = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*resendTime){//60*1000
                return AjaxResult.me().setSuccess(false).setMessage("不行傻鸟！");
            }
        }
        //将验证码记录进redis
        redisTemplate.opsForValue().set(key, code+":"+System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);

        //调用短信接口发送验证码 %s 占位符
        String content = String.format("您的验证码为%s，请在%s分钟之内使用！",code,expireTime);
//        SmsUtil.sendSms(mobile, content);

        System.out.println(content);
        return AjaxResult.me();
    }

    @Override
    @Transactional
    public AjaxResult register(RegisterDto dto) {
        String tel = dto.getTel();
        String password = dto.getPassword();
        String sms = dto.getSms();

        //判空
        if (StringUtils.isEmpty(tel)){
            return AjaxResult.me().setSuccess(false).setMessage("非法参数");
        }
        if (StringUtils.isEmpty(password)){
            return AjaxResult.me().setSuccess(false).setMessage("非法参数");
        }
        if (StringUtils.isEmpty(sms)){
            return AjaxResult.me().setSuccess(false).setMessage("非法参数");
        }
        //获取redis中的验证码
        String key = SmsContants.SMSCODE_KEY + tel;
        String smsCodeOfRedis = (String)redisTemplate.opsForValue().get(key);

        //比对验证码
        if (StringUtils.isEmpty(smsCodeOfRedis)||!smsCodeOfRedis.split(":")[0].equals(sms)){
            return AjaxResult.me().setSuccess(false).setMessage("验证码错误或已经过期！");
        }

        //盐值
        String uuid = UUID.randomUUID().toString();
        String salt = "lusang"+uuid;
        //MD5加密
        String passForMD5 = MD5.getMD5(password+salt);
        //保存loginuser
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername("用户"+tel);
        loginUser.setTel(tel);
        loginUser.setSalt(salt);
        loginUser.setPassword(passForMD5);
        loginUser.setType(0);//1表示管理人员 0表示用户
        AjaxResult ajaxResult = loginUserClient.saveUser(loginUser);
        Object obj = ajaxResult.getResultObj();
        //这里有个坑，Long存放进一个Object的内存中 比如AjaxResult 和map<Sstring,Object>中 再拿出来会降级成为Integer
        Integer loginInteger = (Integer)obj;
        Long loginId = loginInteger.longValue();
        //保存user信息
        User user = new User();
        user.setCreateTime(new Date());
        user.setPhone(tel);
        user.setPassword(passForMD5);
        user.setSalt(salt);
        user.setBitState(1);
        user.setSecLevel(1);
        user.setLoginId(loginId);
        user.setUsername("用户"+tel);
        userMapper.insert(user);
        return AjaxResult.me();
    }
}
